package com.siwei.mes.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.siwei.mes.common.query.PageQuery;
import com.siwei.mes.common.util.InterprectChineseUtils;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.entity.Order;
import com.siwei.mes.entity.OrderClock;
import com.siwei.mes.entity.OrderDetail;
import com.siwei.mes.entity.Project;
import com.siwei.mes.enums.DynamicEnum;
import com.siwei.mes.enums.OrderStatusEnum;
import com.siwei.mes.enums.RoleEnum;
import com.siwei.mes.mapper.ContractMapper;
import com.siwei.mes.mapper.OrderClockMapper;
import com.siwei.mes.mapper.OrderMapper;
import com.siwei.mes.mapper.ProjectMapper;
import com.siwei.mes.service.AuthService;
import com.siwei.mes.service.OrderDetailService;
import com.siwei.mes.service.OrderDynamicService;
import com.siwei.mes.service.OrderService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * 工单(Order)表服务实现类
 *
 * @author makejava
 * @since 2023-12-05 09:31:30
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderDynamicService orderDynamicService;
    @Resource
    private ContractMapper contractMapper;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private AuthService authService;
    @Resource
    private OrderClockMapper orderClockMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long create(Order entity) {
        assertTrue(!RoleEnum.TEAM_LEADER.getCode().equals(authService.getLoginUserRole()), "您不是外检组长,不能新建工单!");
        entity.init(true);
        assertTrue(contractMapper.loadById(entity.getContractId()) == null, "合同信息不存在");
        Project project = projectMapper.loadById(entity.getProjectId());
        assertTrue(project == null, "工程信息不存在");
        entity.setProjectInfo(JsonUtils.beanToObject(project));
        orderMapper.insertSelective(entity);
        /**新增动态*/
        orderDynamicService.insertLog(entity.getId(), DynamicEnum.ORDER_NEW);
        /**新增工单详情*/
        orderDetailService.insertDetail(entity, true);
        return entity.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Order entity) {
        assertTrue(contractMapper.loadById(entity.getContractId()) == null, "合同信息不存在");
        assertTrue(projectMapper.loadById(entity.getProjectId()) == null, "工程信息不存在");

        Order order = orderMapper.selectByPrimaryKey(entity.getId());
        assertTrue(order == null, "工单信息不存在");
        entity.init(false);
        orderMapper.updateByPrimaryKeySelective(entity);
        /**工单详情*/
        orderDetailService.insertDetail(entity, false);
    }

    @Override
    public void delete(Long id) {
        Order order = orderMapper.selectByPrimaryKey(id);
        assertTrue(order == null, "工单信息不存在");
        orderMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo<Order> getPage(PageQuery<Order, Order> query) {
        Order searchParam = query.getParams();
        PageInfo<Order> pageInfo = PageHelper.startPage(query.getPageNum(), query.getPageSize())
                .doSelectPageInfo(() -> orderMapper.getList(searchParam));
        for (Order order : pageInfo.getList()) {
            OrderDetail orderDetail = orderDetailService.payloadDetail(order);
            if (orderDetail != null) {
                order.setOrderDetail(orderDetail);
                order.setDetailInfo(orderDetail.getDetailJson());
                order.setDetailFileInfo(orderDetail.getDetailFile());
            }
        }
        return pageInfo;
    }

    @Override
    public Order loadById(Long id) {
        Order order = orderMapper.loadById(id);
        if (order != null) {
            OrderDetail orderDetail = orderDetailService.payloadDetail(order);
            if (orderDetail != null) {
                order.setOrderDetail(orderDetail);
                order.setDetailInfo(orderDetail.getDetailJson());
                order.setDetailFileInfo(orderDetail.getDetailFile());
            }
            List<OrderClock> list = orderClockMapper.getList(new OrderClock().setOrderId(id));
            if(CollectionUtils.isNotEmpty(list)) {
                order.setClockAddress(list.get(0).getClockAddress());
            }
        }
        return order;
    }

    @Override
    public List<Order> getAll(Order entity) {
        List<Order> list = orderMapper.getList(entity);
        for (Order order : list) {
            OrderDetail orderDetail = orderDetailService.payloadDetail(order);
            if (orderDetail != null) {
                order.setOrderDetail(orderDetail);
                order.setDetailInfo(orderDetail.getDetailJson());
                order.setDetailFileInfo(orderDetail.getDetailFile());
            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transfer(Order entity) {
        assertTrue(!RoleEnum.TEAM_LEADER.getCode().equals(authService.getLoginUserRole()), "您不是外检组长,不能转派工单!");
        Order order = orderMapper.selectByPrimaryKey(entity.getId());
        assertTrue(order == null, "工单信息不存在");
        entity.init(false);
        orderMapper.updateByPrimaryKeySelective(entity);
        orderDynamicService.insertLog(entity.getId(), DynamicEnum.ORDER_TRANSFER);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finish(Order entity) {
        Order order = orderMapper.selectByPrimaryKey(entity.getId());
        assertTrue(order == null, "工单信息不存在");
        entity.init(false);
        entity.setOrderStatus(OrderStatusEnum.FINISH.getCode());
        entity.setFinishServiceTime(new Date());
        entity.setFinishId(authService.getLoginUserId());
        entity.setFinishName(authService.getLoginUserName());
        entity.setFinishTime(new Date());
        orderMapper.updateByPrimaryKeySelective(entity);
        orderDynamicService.insertLog(entity.getId(), DynamicEnum.ORDER_FINISH);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void accept(Order entity) {
        Order order = orderMapper.selectByPrimaryKey(entity.getId());
        assertTrue(order == null, "工单信息不存在");
        entity.init(false);
        entity.setStartServiceTime(new Date());
        entity.setOrderStatus(OrderStatusEnum.ACCEPT.getCode());
        entity.setAcceptId(authService.getLoginUserId());
        entity.setAcceptName(authService.getLoginUserName());
        entity.setAcceptTime(new Date());
        orderMapper.updateByPrimaryKeySelective(entity);
        orderDynamicService.insertLog(entity.getId(), DynamicEnum.ORDER_ACCEPT);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refuse(Order entity) {
        Order order = orderMapper.selectByPrimaryKey(entity.getId());
        assertTrue(order == null, "工单信息不存在");
        entity.init(false);
        entity.setOrderStatus(OrderStatusEnum.REFUSE.getCode());
        entity.setRefuseId(authService.getLoginUserId());
        entity.setRefuseName(authService.getLoginUserName());
        entity.setRefuseTime(new Date());
        orderMapper.updateByPrimaryKeySelective(entity);
        orderDynamicService.insertLog(entity.getId(), DynamicEnum.ORDER_REFUSE);
    }
}
